package api

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"gitee.com/lv-forever/open-ai-api/config"
)

const CODERUTIL_URL = "https://www.coderutil.com/api/openai/getToken/"

type ErrorResp struct {
	Success bool    `json:"success"`
	Code    int     `json:"code"`
	Msg     string  `json:"msg"`
	Data    float32 `json:"data"`
}

func GetAPIKey() (string, error) {
	//Init config Param
	configuration := config.LoadConfig()

	// create URL params
	data := url.Values{}
	data.Set("access-key", configuration.AccessKey)
	data.Set("secret-key", configuration.SecretKey)

	u, err := url.ParseRequestURI(CODERUTIL_URL)
	if err != nil {
		fmt.Printf("parse url requestUrl failed,err:%v\n", err)
	}

	u.RawQuery = data.Encode() // URL encode
	// fmt.Println(u.String())
	resp, err := http.Get(u.String())
	if err != nil {
		fmt.Printf("post failed, err:%v\n", err)
		return "", errors.New(fmt.Sprintf("post failed, err:%v\n", err))
	}
	defer resp.Body.Close()

	apiKey, err := io.ReadAll(resp.Body)
	var errorResp ErrorResp
	err = json.Unmarshal(apiKey, &errorResp)
	if err != nil {
		return string(apiKey), nil
	}
	return "", errors.New(fmt.Sprintf("CoderUtil post failed, err:%v\n", errorResp.Msg))
}
